package com.dalei.vds.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.dalei.vds.database.LogDatabaseHelper;
import com.dalei.vds.model.Log;
import com.dalei.vdserver.shared.model.VehicleInformation;

public class LogDao {

	private LogDatabaseHelper helper;

	public LogDao(Context context) {
		// TODO Auto-generated constructor stub
		helper = new LogDatabaseHelper(context);
	}

	public int getCountByTime(Date start, Date end) {
		String startTime = (new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss",
				Locale.CHINA).format(start));
		String endTime = (new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss",
				Locale.CHINA).format(end));
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.query(LogDatabaseHelper.TABLE_LOG,
				new String[] { "COUNT(*)" }, "_timeStamp>=? AND _timeStamp<=?",
				new String[] { startTime, endTime }, null, null, null);
		cursor.moveToNext();
		int count = cursor.getInt(0);
		cursor.close();
		db.close();
		return count;
	}

	public long saveLog(Log log) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();

		VehicleInformation vi = log.getVehicleInformation();
		values.put("_id", vi.getId());
		values.put("_licensePlateNumber", vi.getLicensePlateNumber());
		values.put("_licensePlateType", vi.getLicensePlateType());
		values.put("_vin", vi.getVin());
		values.put("_vehicleType", vi.getVehicleType());
		values.put("_brandAndModel", vi.getBrandAndModel());
		values.put("_bodyColor", vi.getBodyColor());
		values.put("_engineModel", vi.getEngineModel());
		values.put("_fuelType", vi.getFuelType());
		values.put("_owners", vi.getOwners());
		values.put("_registrationDate", new SimpleDateFormat(
				"yyyy-MM-dd, hh:mm:ss", Locale.CHINA).format(vi
				.getRegistrationDate()));
		long rowAffected = db.insert(
				LogDatabaseHelper.TABLE_VEHICLE_INFORMATION, null, values);

		values.clear();

		values.put("_fid", log.getFid());
		values.put("_vehicleInformationId", vi.getId());
		values.put("_worker", log.getWorker());
		values.put("_timeStamp", new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss",
				Locale.CHINA).format(log.getTimeStamp()));
		rowAffected = rowAffected
				+ db.insert(LogDatabaseHelper.TABLE_LOG, null, values);

		db.close();
		return rowAffected;
	}
}
